﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Web;
using System.Threading;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using Newtonsoft.Json.Linq;

namespace QiangPiaoTool
{
    partial class Form1
    {
        string stationAllText = string.Empty;
        private bool Login()
        {
            bool result = false;
            try
            {
                ShowMsg("正在登陆……");
                //1 获取随机码 {"loginRand":"364","randError":"Y"}
                string randRefUrl = "https://dynamic.12306.cn/otsweb/loginAction.do?method=init";
                string randUrl = "https://dynamic.12306.cn/otsweb/loginAction.do?method=loginAysnSuggest";
                string randJson = HttpHelper.GetString("GET", randRefUrl, randUrl, null, _cc);
                string loginRand = randJson.Split('"')[3];

                //2 登陆
                string loginRefUrl = "https://dynamic.12306.cn/otsweb/loginAction.do?method=init";
                string loginUrl = "https://dynamic.12306.cn/otsweb/loginAction.do?method=login";
                StringBuilder loginParas = new StringBuilder();
                loginParas.AppendFormat("loginRand={0}", loginRand);
                loginParas.Append("&refundLogin=N");
                loginParas.Append("&refundFlag=Y");
                loginParas.AppendFormat("&loginUser.user_name={0}", user.Name);
                loginParas.Append("&nameErrorFocus=");
                loginParas.AppendFormat("&user.password={0}", user.Password);
                loginParas.Append("&passwordErrorFocus=");
                loginParas.AppendFormat("&randCode={0}", loginRandCode);
                loginParas.Append("&randErrorFocus=");

                string loginResult = HttpHelper.GetString("POST", loginRefUrl, loginUrl, loginParas.ToString(), _cc);
                if (loginResult.Contains("当前访问用户过多"))
                {
                    ShowMsg("当前访问用户过多");
                }
                else if (loginResult.Contains("请输入正确的验证码"))
                {
                    ShowMsg("请输入正确的验证码");
                }
                else if (loginResult.Contains("您好"))
                {
                    result = true;
                    ShowMsg("登陆成功");
                }
                else
                {
                    ShowMsg("登陆失败:" + loginResult);
                }
            }
            catch (Exception ex)
            {
                ShowMsg("登陆失败:" + ex.Message);
            }
            return result;
        }

        private bool loadTrainList()
        {
            try
            {
                ShowMsg("正在查询列车……");
                //清空trainList
                this.Invoke(new Action(() =>
                {
                    dgvTrainList.AutoGenerateColumns = false;
                    dgvTrainList.DataSource = new BindingList<Train>();
                    trainList.Clear();
                }));

                string epoch = ((DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000000).ToString();
                //加载列车信息
                StringBuilder trainListParas = new StringBuilder();

           
                trainListParas.Append("https://dynamic.12306.cn/otsweb/order/querySingleAction.do?");
                trainListParas.Append("method=queryLeftTicket");
                trainListParas.AppendFormat("&orderRequest.train_date={0}", plan.TrainDate);
                trainListParas.AppendFormat("&orderRequest.from_station_telecode={0}", getStationCode(plan.StartStation));
                trainListParas.AppendFormat("&orderRequest.to_station_telecode={0}", getStationCode(plan.EndStation));

                trainListParas.Append("&orderRequest.train_no=");
                trainListParas.Append("&trainPassType=QB");
                trainListParas.AppendFormat("&trainClass={0}", HttpUtility.UrlEncode("QB#D#Z#T#K#QT#"));
                trainListParas.Append("&includeStudent=00");
                trainListParas.Append("&seatTypeAndNum=");
                trainListParas.AppendFormat("&orderRequest.start_time_str={0}", HttpUtility.UrlEncode("00:00--24:00"));
            
               // trainListParas.AppendFormat("&_={0}", epoch);//防止缓存

                string trainListRefUrl = "https://dynamic.12306.cn/otsweb/order/querySingleAction.do?method=init";
                string trainListUrl = trainListParas.ToString();
            
                string trainListStr = HttpHelper.GetString("GET", trainListRefUrl, trainListUrl, null, _cc);
                trainListStr = trainListStr.Replace("&nbsp;", "");
                string[] trainsArr = trainListStr.Split('订');

                trainList = new BindingList<Train>();
                for (int i = 0; i < trainsArr.Length - 1; i++)
                {
                    //一张票都没有的就不显示了
                    if (!trainsArr[i].Contains("onclick"))
                    {
                        continue;
                    }

                    int leftIndex = trainsArr[i].IndexOf("getSelected('") + 13;
                    int rightIndex = trainsArr[i].IndexOf("')>预");
                    string trainStr = trainsArr[i].Substring(leftIndex, rightIndex - leftIndex);
                    string[] trainInfoArr = trainStr.Split('#');

                    Train train = new Train();
                    train.TrainCode = trainInfoArr[0].Trim();
                    train.LiShi = trainInfoArr[1].Trim();
                    train.StartTime = trainInfoArr[2].Trim();
                    train.TrainNo4 = trainInfoArr[3].Trim();
                    train.StartStationCode = trainInfoArr[4].Trim();
                    train.EndStationCode = trainInfoArr[5].Trim();
                    train.EndTime = trainInfoArr[6].Trim();
                    train.StartStationName = trainInfoArr[7].Trim();
                    train.EndStationName = trainInfoArr[8].Trim();
                    train.StartStationNo = trainInfoArr[9].Trim();
                    train.EndStationNo = trainInfoArr[10].Trim();
                    train.YpInfoDetail = trainInfoArr[11].Trim();
                    train.MmStr = trainInfoArr[12].Trim();
                    train.LocationCode = trainInfoArr[13].Trim();

                    int leftIndexYp = trainsArr[i].IndexOf(train.EndTime + "," + train.LiShi) + 12;
                    int rightIndexYp = trainsArr[i].IndexOf("onclick");
                    String ytInfoStr = trainsArr[i].Substring(leftIndexYp, rightIndexYp - leftIndexYp);

                    List<string> ypCountList = ytInfoStr.Split(',').ToList();
                    ypCountList.RemoveAt(ypCountList.Count - 1);
                    ypCountList = ypCountList.Select(_ => siftYpCount(_)).ToList();

                    train.YpBusiness = ypCountList[0];
                    train.YpSpecial = ypCountList[1];
                    train.YpOne = ypCountList[2];
                    train.YpTwo = ypCountList[3];
                    train.YpAdvancedSleeper = ypCountList[4];
                    train.YpSoftSleeper = ypCountList[5];
                    train.YpHardSleeper = ypCountList[6];
                    train.YpSoftSeat = ypCountList[7];
                    train.YpHardSeat = ypCountList[8];
                    train.YpNoSeat = ypCountList[9];
                    train.YpOther = ypCountList[10];

                    trainList.Add(train);
                }

                this.Invoke(new Action(() =>
                {
                    dgvTrainList.AutoGenerateColumns = false;
                    dgvTrainList.DataSource = trainList;

                }));
                ShowMsg("查询列车成功");
                return true;

            }
            catch (Exception ex)
            {
                ShowMsg("查询列车失败：" + ex.Message);
                return false;
            }
        }

        private bool loadLoginPassCode()
        {
            try
            {
                ShowMsg("正在加载登陆验证码");
                //2013/01/18  12306增强安全机制
                //string jsCkRefUrl = "http://www.12306.cn/mormhweb/kyfw/";
                //string jsCkUrl = "https://dynamic.12306.cn/otsweb/ ";

                //string jsCkRefUrl = "https://dynamic.12306.cn/otsweb/";
                //string jsCkUrl = "https://dynamic.12306.cn/otsweb/loginAction.do?method=init";
                //HttpHelper.GetStream("GET", jsCkRefUrl, jsCkUrl, null, _cc);

                string passRefUrl = "https://dynamic.12306.cn/otsweb/loginAction.do?method=init";
                string passUrl = "https://dynamic.12306.cn/otsweb/passCodeAction.do?rand=sjrand";
                Stream imgStream = HttpHelper.GetStream("GET", passRefUrl, passUrl, null, _cc);
                this.Invoke(new Action(() =>
                {
                    pbxLoginPassCode.Image = Image.FromStream(imgStream);
                    ShowMsg("请填写登陆验证码");

                }));
                return true;
            }
            catch (Exception ex)
            {
                ShowMsg("加载验证码失败" + ex.Message);
                return false;
            }
        }

        private string getStationCode(string stationText)
        {
            try
            {
                //加载站名
                if (string.IsNullOrEmpty(stationAllText))
                {
                    stationAllText = File.ReadAllText(Application.StartupPath + "\\station_name.js");
                }
                string[] allStation = stationAllText.Split('|');
                int prevIndex = allStation.Select((i, j) => new { Value = i, Index = j }).Where(_ => _.Value == stationText.Trim()).First().Index;
                string stationCode = allStation[prevIndex + 1];

                ShowMsg("得到" + stationText + "的城市码:" + stationCode);
                return stationCode;
            }
            catch (Exception ex)
            {
                ShowMsg("加载城市码失败:" + ex.Message);
                return "";
            }
        }

        private bool subOrderRequest()
        {
            try
            {
                ShowMsg("正在进行预处理");
                                           
                string subOrderRequestRefUrl = "https://dynamic.12306.cn/otsweb/order/querySingleAction.do?method=init";
                string subOrderRequestUrl = "https://dynamic.12306.cn/otsweb/order/querySingleAction.do?method=submutOrderRequest";
                                       
                StringBuilder subOrderRequestParas = new StringBuilder();
                subOrderRequestParas.AppendFormat("station_train_code={0}", selectedTrain.TrainCode);
                subOrderRequestParas.AppendFormat("&train_date={0}", plan.TrainDate);
                subOrderRequestParas.Append("&seattype_num=");
                subOrderRequestParas.AppendFormat("&from_station_telecode={0}", selectedTrain.StartStationCode);
                subOrderRequestParas.AppendFormat("&to_station_telecode={0}", selectedTrain.EndStationCode);
                subOrderRequestParas.Append("&include_student=00");
                subOrderRequestParas.AppendFormat("&from_station_telecode_name={0}", selectedTrain.StartStationName);
                subOrderRequestParas.AppendFormat("&to_station_telecode_name={0}", selectedTrain.EndStationName);
                subOrderRequestParas.AppendFormat("&round_train_date={0}", plan.TrainDate);
                subOrderRequestParas.Append("&round_start_time_str=00:00--24:00");
                subOrderRequestParas.Append("&single_round_type=1");
                subOrderRequestParas.Append("&train_pass_type=QB");
                subOrderRequestParas.Append("&train_class_arr=QB#D#Z#T#K#QT#");
                subOrderRequestParas.Append("&start_time_str=00:00--24:00");
                subOrderRequestParas.AppendFormat("&lishi={0}", selectedTrain.LiShi);//2013-01-18修改
                subOrderRequestParas.AppendFormat("&train_start_time={0}", selectedTrain.StartTime);
                subOrderRequestParas.AppendFormat("&trainno4={0}", selectedTrain.TrainNo4);
                subOrderRequestParas.AppendFormat("&arrive_time={0}", selectedTrain.EndTime);
                subOrderRequestParas.AppendFormat("&from_station_name={0}", selectedTrain.StartStationName);
                subOrderRequestParas.AppendFormat("&to_station_name={0}", selectedTrain.EndStationName);
                subOrderRequestParas.AppendFormat("&from_station_no={0}", selectedTrain.StartStationNo);
                subOrderRequestParas.AppendFormat("&to_station_no={0}", selectedTrain.EndStationNo);
                subOrderRequestParas.AppendFormat("&ypInfoDetail={0}", selectedTrain.YpInfoDetail);
                subOrderRequestParas.AppendFormat("&mmStr={0}", selectedTrain.MmStr);
                subOrderRequestParas.AppendFormat("&locationCode={0}", selectedTrain.LocationCode);
                string epoch = ((DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000000).ToString();
               // subOrderRequestParas.AppendFormat("&_={0}", epoch);//防止缓存
                string initContent = HttpHelper.GetString("POST", subOrderRequestRefUrl, subOrderRequestUrl, subOrderRequestParas.ToString(), _cc);

                //请求数据
                string initRefUrl="https://dynamic.12306.cn/otsweb/order/querySingleAction.do?method=init";
                string initUrl = "https://dynamic.12306.cn/otsweb/order/confirmPassengerAction.do?method=init";
                initContent=HttpHelper.GetString("GET",initRefUrl,initUrl,null,_cc);

                if (initContent.Contains("left_ticket"))
                {
                    leftTicketStr = initContent.Substring(initContent.IndexOf("left_ticket")).Split('"')[2];
                    strutsToken = initContent.Substring(initContent.IndexOf("org.apache.struts.taglib.html.TOKEN")).Split('"')[2];
                    ShowMsg("预处理成功");
                    return true;
                }

                else if (initContent.Contains("var message ="))
                {
                    int warnLeftIndex = initContent.IndexOf("var message =") + 13;
                    int warnRightIndex = initContent.IndexOf("var messageShow");
                    string warnMsg = initContent.Substring(warnLeftIndex, warnRightIndex - warnLeftIndex);
                    ShowMsg("预处理失败。" + warnMsg);
                    return false;
                }
                else
                {
                    ShowMsg("预处理失败。" + initContent);
                    return false;
                }
            }
            catch (Exception ex)
            {
                ShowMsg("可能由于网络原因，预处理失败：" + ex.Message + ",请重试");
                return false;
            }
        }

        private bool loadSumitPassCode()
        {
            try
            {
                ShowMsg("正在加载提交验证码");
                string passCodeRefUrl = "https://dynamic.12306.cn/otsweb/order/confirmPassengerAction.do?method=init";
                string passCodeUrl = "https://dynamic.12306.cn/otsweb/passCodeAction.do?rand=randp";
                                    
                Stream imgStream = HttpHelper.GetStream("GET", passCodeRefUrl, passCodeUrl, null, _cc);
                this.Invoke(new Action(() =>
                {
                    pbxSumitPassCode.Image = Image.FromStream(imgStream);
                }));
                ShowMsg("请输入提交验证码");
                return true;
            }
            catch (Exception ex)
            {
                ShowMsg("加载提交验证码失败：" + ex.Message);
                return false;
            }
        }

        private string buildSubmitParas()
        {

            StringBuilder checkOrderInfoParas = new StringBuilder();
            checkOrderInfoParas.Append("checkbox0=0");

            //-----------------------------------------
            checkOrderInfoParas.Append("&checkbox9=Y");
            checkOrderInfoParas.Append("&checkbox9=Y");
            checkOrderInfoParas.Append("&checkbox9=Y");
            checkOrderInfoParas.Append("&checkbox9=Y");
            checkOrderInfoParas.Append("&checkbox9=Y");
            //-----------------------------------------
       
            checkOrderInfoParas.AppendFormat("&leftTicketStr={0}", leftTicketStr);


            //checkOrderInfoParas.Append("&oldPassengers=");
            //checkOrderInfoParas.Append("&oldPassengers=");
            //checkOrderInfoParas.Append("&oldPassengers=");
            //checkOrderInfoParas.Append("&oldPassengers=");

            checkOrderInfoParas.Append("&orderRequest.bed_level_order_num=000000000000000000000000000000");
            checkOrderInfoParas.Append("&orderRequest.cancel_flag=1");
            checkOrderInfoParas.AppendFormat("&orderRequest.end_time={0}", selectedTrain.EndTime);
            checkOrderInfoParas.AppendFormat("&orderRequest.from_station_name={0}", selectedTrain.StartStationName);
            checkOrderInfoParas.AppendFormat("&orderRequest.from_station_telecode={0}", selectedTrain.StartStationCode);
            checkOrderInfoParas.Append("&orderRequest.id_mode=Y");
            checkOrderInfoParas.Append("&orderRequest.reserve_flag=A");
            checkOrderInfoParas.Append("&orderRequest.seat_detail_type_code=");
            checkOrderInfoParas.Append("&orderRequest.seat_type_code=");
            checkOrderInfoParas.AppendFormat("&orderRequest.start_time={0}", selectedTrain.StartTime);
            checkOrderInfoParas.AppendFormat("&orderRequest.station_train_code={0}", selectedTrain.TrainCode);
            checkOrderInfoParas.Append("&orderRequest.ticket_type_order_num=");
            checkOrderInfoParas.AppendFormat("&orderRequest.to_station_name={0}", selectedTrain.EndStationName);
            checkOrderInfoParas.AppendFormat("&orderRequest.to_station_telecode={0}", selectedTrain.EndStationCode);
            checkOrderInfoParas.AppendFormat("&orderRequest.train_date={0}", plan.TrainDate);
            checkOrderInfoParas.AppendFormat("&orderRequest.train_no={0}", selectedTrain.TrainNo4);
            checkOrderInfoParas.AppendFormat("&org.apache.struts.taglib.html.TOKEN={0}", strutsToken);

            for (int i = 0; i < personList.Count; i++)
            {
                Person p = personList[i];
                checkOrderInfoParas.AppendFormat("&passenger_{0}_cardno={1}", i + 1, p.IdentityCard);
                checkOrderInfoParas.AppendFormat("&passenger_{0}_cardtype=1", i + 1);
                checkOrderInfoParas.AppendFormat("&passenger_{0}_mobileno={1}", i + 1, p.Phone);
                checkOrderInfoParas.AppendFormat("&passenger_{0}_name={1}", i + 1, p.PersonName);
                checkOrderInfoParas.AppendFormat("&passenger_{0}_seat={1}", i + 1, plan.SeatType);//硬座  1 ,硬卧 3,软卧4
                checkOrderInfoParas.AppendFormat("&passenger_{0}_seat_detail=0", i+1);
                checkOrderInfoParas.AppendFormat("&passenger_{0}_ticket=1", i + 1);
                //
                checkOrderInfoParas.AppendFormat("&oldPassengers={0},1,{1}", p.PersonName, p.IdentityCard);
                checkOrderInfoParas.AppendFormat("&passengerTickets={3},0,1,{0},1,{1},{2},Y", p.PersonName, p.IdentityCard, p.Phone, plan.SeatType);
            }
            for (int i = 0; i < 5-personList.Count; i++)
            {
                checkOrderInfoParas.Append("&oldPassengers=");
            }

            checkOrderInfoParas.AppendFormat("&randCode={0}", submitRandCode);
            checkOrderInfoParas.Append("&textfield=中文或拼音首字母");


            return checkOrderInfoParas.ToString();
        }

        private bool checkOrderInfo()
        {
            try
            {
                ShowMsg("开始检查订单");
                string checkOrderInfoRefUrl = "https://dynamic.12306.cn/otsweb/order/confirmPassengerAction.do?method=init";
                string checkOrderInfoUrl = "https://dynamic.12306.cn/otsweb/order/confirmPassengerAction.do?method=checkOrderInfo&rand=" + submitRandCode;
                string patas = buildSubmitParas();
                patas += "&tFlag=dc";
                string resultJson = HttpHelper.GetString("POST", checkOrderInfoRefUrl, checkOrderInfoUrl, patas, _cc);
                JObject json = JObject.Parse(resultJson);
                string errMsg = (string)json["errMsg"];

                ShowMsg(resultJson);
                //if (errMsg == "Y")
                //{
                  
                //    return true;
                //}
                //else 
                //{
                //    ShowMsg("检查订单失败：" + errMsg);
                //    return false;
                //}
                return true;
            }
            catch (Exception ex)
            {
                ShowMsg("检查订单失败：" + ex.Message);
                return false;
            }
        }

        private bool getQueueCount()
        {
            try
            {
                ShowMsg("正在获取当前队列长度信息");
                string refUrl = "https://dynamic.12306.cn/otsweb/order/confirmPassengerAction.do?method=init";
                StringBuilder paras = new StringBuilder();

                paras.AppendFormat("https://dynamic.12306.cn/otsweb/order/confirmPassengerAction.do?method=getQueueCount");
                paras.AppendFormat("&train_date={0}", plan.TrainDate);
                paras.AppendFormat("&train_no={0}", selectedTrain.TrainNo4);
                paras.AppendFormat("&station={0}", selectedTrain.TrainCode);
                paras.AppendFormat("&seat={0}",plan.SeatType);
                paras.AppendFormat("&from={0}", selectedTrain.StartStationCode);
                paras.AppendFormat("&to={0}", selectedTrain.EndStationCode);
                paras.AppendFormat("&ticket={0}", leftTicketStr);

                string resultJson = HttpHelper.GetString("GET", refUrl, paras.ToString(), null, _cc);
                ShowMsg("获取队列长度信息：" + resultJson);
                return true;
            }
            catch (Exception ex)
            {
                ShowMsg("获取队列长度失败" + ex.Message);
                return false;
            }
        }

        private bool confirmSingleForQueueOrder()
        {
            try
            {
                ShowMsg("已经进入最后一步，正在提交订单");
                string refUrl = "https://dynamic.12306.cn/otsweb/order/confirmPassengerAction.do?method=init";
               // string url = "https://dynamic.12306.cn/otsweb/order/confirmPassengerAction.do?method=confirmSingleForQueueOrder";

                string url = "https://dynamic.12306.cn/otsweb/order/confirmPassengerAction.do?method=confirmSingleForQueue";

                string paras = buildSubmitParas();

                string resultJson = HttpHelper.GetString("POST", refUrl, url, paras, _cc);

                JObject json = JObject.Parse(resultJson);
                string errMsg = (string)json["errMsg"];
                if (errMsg == "Y")
                {
                    ShowMsg("提交订单成功");
                    return true;
                }
                else
                {
                    ShowMsg("提交订单失败：" + errMsg);
                    return false;
                }
            }
            catch (Exception ex)
            {
                ShowMsg("提交订单失败：" + ex.Message);
                return false;
            }
        }

        private bool checkOrder()
        {
            try
            {
                ShowMsg("正在检测订票结果");
                string checkRefUrl = "https://dynamic.12306.cn/otsweb/order/confirmPassengerAction.do?method=init";
               // string checkUrl = "https://dynamic.12306.cn/otsweb/order/myOrderAction.do?method=getOrderWaitTime&tourFlag=dc";
                string checkUrl = "https://dynamic.12306.cn/otsweb/order/myOrderAction.do?method=queryOrderWaitTime&tourFlag=dc";
                string resultJson = HttpHelper.GetString("GET", checkRefUrl, checkUrl, null, _cc);
                JObject json = JObject.Parse(resultJson);
                JToken token = json["orderId"];

                if (token == null)
                {
                    ShowMsg("waitTime:" + (string)json["waitTime"] + "waitCount:" + (string)json["waitCount"]);
                }
                else
                {
                    ShowMsg("恭喜！订票成功,订单号:" + (string)json["orderId"] + ",请立马登陆12306网站完成付款");
                
                }
                return token != null;
            }
            catch (Exception ex)
            {
                ShowMsg("检测订票结果失败：" + ex.Message);
                return false;
            }
        }

        private void ShowMsg(string msg)
        {
            this.Invoke(new Action(() =>
            {
                if (rtbMsg.TextLength > 10000)
                {
                    rtbMsg.Clear();
                }
                this.rtbMsg.AppendText("[" + DateTime.Now.ToString() + "]" + "\n" + "   " + msg + "\n");
                rtbMsg.ScrollToCaret();
            }));
        }

        public static string GetMiddleValue(string str, string s, string e)
        {
            Regex rg = new Regex("(?<=(" + s + "))[.\\s\\S]*?(?=(" + e + "))");
            return rg.Match(str).Value;
        }

        /// <summary>
        /// 过滤无用的字符
        /// </summary>
        /// <param name="i"></param>
        /// <returns></returns>
        private string siftYpCount(string i)
        {
            if (i.Contains(">"))
            {
                return i.Split('>', '<')[2];
            }
            else
            {
                return i;
            }
        }

        public void reLoadPersonList()
        {
            try
            {
                personList = new List<Person>();
                foreach (DataGridViewRow row in dgvPersonList.Rows)
                {
                    if (row.Cells[0].Value != null && row.Cells[1].Value != null && row.Cells[2].Value != null)
                    {
                        Person p = new Person();
                        p.PersonName = row.Cells[0].Value.ToString();
                        p.IdentityCard = row.Cells[1].Value.ToString();
                        p.Phone = row.Cells[2].Value.ToString();
                        personList.Add(p);
                    }
                }
                Serializer.Serialize(Application.StartupPath + "\\per.li", personList);
            }
            catch
            {

            }
        }

        public void enterMonitor(string msg)
        {
            DialogResult noPresult = MessageBox.Show(msg, "确认", MessageBoxButtons.OKCancel);
            if (noPresult.ToString() == "OK")
            {
                //自动监控
                tmMonitor.Enabled = true;
                groupBox2.Enabled = false;
                btnMonitor.Visible = true;
                ShowMsg("已经启动自动监控，有票时将自动通知你，到时直接输入验证码点击提交");
            }

        }

        public string getSeatTypeByCombIndex(int index)
        {
            switch (index)
            {
                case 0: plan.SeatType = "9"; return "商务座";
                case 1: plan.SeatType = "P"; return "特等座";
                case 2: plan.SeatType = "M"; return "一等座";
                case 3: plan.SeatType = "O"; return "二等座";
                case 4: plan.SeatType = "6"; return "高级软卧";
                case 5: plan.SeatType = "4"; return "软卧";
                case 6: plan.SeatType = "3"; return "硬卧";
                case 7: plan.SeatType = "2"; return "软座";
                case 8: plan.SeatType = "1"; return "硬座";
                case 9: plan.SeatType = "-1"; return "无座";
                default: plan.SeatType = "1"; return "硬座";
            }

        }

        public void autoSelect()
        {
            if (string.IsNullOrEmpty(txtStartStation.Text) || string.IsNullOrEmpty(txtEndStation.Text.Trim()))
            {
                ShowMsg("请填写乘车区间");
                return;
            }
            else if (!hasLogin)
            {
                ShowMsg("您还没登陆，请先登录");
                return;
            }
            bool hasYp = false;
            //加载类型
            //查询时候只需要乘车计划的这三项
            plan.StartStation = txtStartStation.Text.Trim();
            plan.EndStation = txtEndStation.Text.Trim();
            plan.TrainDate = dtpDate.Value.ToString("yyyy-MM-dd");
            getSeatTypeByCombIndex(cbxSeatType.SelectedIndex);
            plan.TrainCode = txtTainCode.Text.Trim();

            ThreadPool.QueueUserWorkItem(new WaitCallback(_ =>
          {
              bool isQuerySuc = loadTrainList();

              if (isQuerySuc && !string.IsNullOrEmpty(plan.TrainCode) && !string.IsNullOrEmpty(plan.SeatType))
              {
                  switch (plan.SeatType)
                  {
                      case "9": hasYp = trainList.Where(i => i.TrainCode == plan.TrainCode && !i.YpBusiness.Contains("无") && !i.YpBusiness.Contains("*") && !i.YpBusiness.Contains("-")).Count() > 0; break;
                      case "P": hasYp = trainList.Where(i => i.TrainCode == plan.TrainCode && !i.YpSpecial.Contains("无") && !i.YpSpecial.Contains("*") && !i.YpSpecial.Contains("-")).Count() > 0; break;
                      case "M": hasYp = trainList.Where(i => i.TrainCode == plan.TrainCode && !i.YpOne.Contains("无") && !i.YpOne.Contains("*") && !i.YpOne.Contains("-")).Count() > 0; break;
                      case "O": hasYp = trainList.Where(i => i.TrainCode == plan.TrainCode && !i.YpTwo.Contains("无") && !i.YpTwo.Contains("*") && !i.YpTwo.Contains("-")).Count() > 0; break;
                      case "6": hasYp = trainList.Where(i => i.TrainCode == plan.TrainCode && !i.YpAdvancedSleeper.Contains("无") && !i.YpAdvancedSleeper.Contains("*") && !i.YpAdvancedSleeper.Contains("-")).Count() > 0; break;
                      case "4": hasYp = trainList.Where(i => i.TrainCode == plan.TrainCode && !i.YpSoftSleeper.Contains("无") && !i.YpSoftSleeper.Contains("*") && !i.YpSoftSleeper.Contains("-")).Count() > 0; break;
                      case "3": hasYp = trainList.Where(i => i.TrainCode == plan.TrainCode && !i.YpHardSleeper.Contains("无") && !i.YpHardSleeper.Contains("*") && !i.YpHardSleeper.Contains("-")).Count() > 0; break;
                      case "2": hasYp = trainList.Where(i => i.TrainCode == plan.TrainCode && !i.YpSoftSeat.Contains("无") && !i.YpSoftSeat.Contains("*") && !i.YpSoftSeat.Contains("-")).Count() > 0; break;
                      case "1": hasYp = trainList.Where(i => i.TrainCode == plan.TrainCode && !i.YpHardSeat.Contains("无") && !i.YpHardSeat.Contains("*") && !i.YpHardSeat.Contains("-")).Count() > 0; break;
                      case "-1": hasYp = trainList.Where(i => i.TrainCode == plan.TrainCode && !i.YpNoSeat.Contains("无") && !i.YpNoSeat.Contains("*") && !i.YpNoSeat.Contains("-")).Count() > 0; break;
                  }
                  if (hasYp)
                  {
                      //播放音乐
                      Sounds.Play("QiangPiaoTool.ypl.wav");

                      this.Invoke(new Action(() =>
                      {
                          //如果自动监控，则取消
                          if (tmMonitor.Enabled)
                          {
                              btnMonitor_Click(null, null);
                          }
                          //弹出窗体
                          this.WindowState = FormWindowState.Normal;
                          //保持最前
                          this.TopMost = true;
                          // 窗体抖动
                          Random ran = new Random((int)DateTime.Now.Ticks);
                          Point point = this.Location;
                          for (int i = 0; i < 8; i++)
                          {
                              this.Location = new Point(point.X + ran.Next(8) - 4, point.Y + ran.Next(8) - 4);
                              System.Threading.Thread.Sleep(15);
                              this.Location = point;
                              System.Threading.Thread.Sleep(15);
                          }

                      }));

                      // 直接进入预处理
                      selectedTrain = trainList.Where(i => i.TrainCode == plan.TrainCode).FirstOrDefault<Train>();

                      bool requestResult = subOrderRequest();
                      if (requestResult)
                      {
                          //加载验证码
                          loadSumitPassCode();
                      }
                  }

              }

          }));

        }


    }
}
